﻿using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using FreeBroker.Properties;

namespace FreeBroker
{
    public partial class SearchForm : Form
    {
        public SearchForm()
        {
            InitializeComponent();
            this.MinimumSize = this.Size;
            this.MaximumSize = this.Size;
            // Set column widths
            string widths = Settings.Default.SearchColumnWidths;
            if (widths != null && widths.Length > 0)
            {
                string[] columns = widths.Split(new char[] { ';' });
                for (int i = 0; i < this.listView.Columns.Count; i++)
                {
                    if (columns.Length == i)
                    {
                        // Cancel interation if more columns than saved widths
                        break;
                    }
                    int width;
                    bool success = int.TryParse(columns[i], out width);
                    if (!success)
                    {
                        // Width part is unparseable -> Set default value
                        width = 50;
                    }
                    this.listView.Columns[i].Width = width;
                }
            }
        }

        private bool expanded;

        private ComDirectSearchResult selectedObject;
        public ComDirectSearchResult SelectedObject
        {
            get { return this.selectedObject; }
        }

        private void buttonSearch_Click(object sender, EventArgs e)
        {
            if (this.buttonSearch.Text.Equals("abbrechen"))
            {
                this.backgroundWorker.CancelAsync();
                this.buttonSearch.Enabled = false;
            }
            else
            {
                string search = this.textBoxSearch.Text;
                if (search.Length > 0)
                {
                    // TODO: Check and replace special characters
                    this.buttonSearch.Text = "abbrechen";
                    this.listView.Items.Clear();
                    this.loadingCircle.FadeIn();
                    backgroundWorker.RunWorkerAsync(search);
                }
            }
        }

        private void textBoxSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                buttonSearch_Click(null, null);
            }
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            ComDirect direct = new ComDirect();
            string content = direct.Search((string)e.Argument);
            if (backgroundWorker.CancellationPending)
            {
                return;
            }

            List<ComDirectSearchResult> results = direct.ParseSearchResultsFromContent(content);
            if (backgroundWorker.CancellationPending)
            {
                return;
            }
            if (results == null || results.Count == 0)
            {
                MessageBox.Show("Es wurden keine Einträge gefunden.");
                return;
            }
            do
            {
                if (backgroundWorker.CancellationPending)
                {
                    return;
                }
                if (results == null)
                {
                    results = direct.ParseSearchResultsFromUri(direct.nextUrl);
                }
                backgroundWorker.ReportProgress(0, results);
                results = null;
            } while (direct.nextUrl != null && !backgroundWorker.CancellationPending);
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.loadingCircle.FadeOut();
            this.buttonSearch.Text = "suchen";
            this.buttonSearch.Enabled = true;
        }

        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.UserState != null)
            {
                if (!expanded)
                {
                    this.MinimumSize = new Size();
                    this.MaximumSize = new Size();
                    Size newSize = Settings.Default.SearchWindowSize;
                    // Set to editor window size
                    this.Size = new Size(625, 460);
                    this.listView.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
                    this.buttonOk.Anchor = AnchorStyles.Left | AnchorStyles.Bottom;
                    this.buttonCancel.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;
                    this.labelCounter.Anchor = AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right;
                    if (newSize != null && !newSize.IsEmpty)
                    {
                        // Now set to last saved size
                        this.Size = newSize;
                    }
                    expanded = true;
                }
                List<ComDirectSearchResult> results = (List<ComDirectSearchResult>)e.UserState;
                foreach (ComDirectSearchResult item in results)
                {
                    string name = Helper.UnescapeHtmlString(item.Name);
                    string type = item.Type == null ? "unbekannt" : item.Type.Name;
                    ListViewItem lvItem = new ListViewItem(new string[] { name, type, item.ActualValue, item.Currency, item.DateTime, item.StockMarket });
                    lvItem.Tag = item;
                    this.listView.Items.Add(lvItem);
                }
                if (this.listView.Items.Count == 1)
                {
                    this.labelCounter.Text = this.listView.Items.Count + " Eintrag";
                }
                else
                {
                    this.labelCounter.Text = this.listView.Items.Count + " Einträge";
                }
                // Select first item automatically
                this.listView.SelectedIndices.Add(0);
            }
        }

        private void listView_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
        {
            StringBuilder builder = new StringBuilder();
            foreach (ColumnHeader item in this.listView.Columns)
            {
                if (builder.Length > 0)
                {
                    builder.Append(";");
                }
                builder.Append(item.Width);
            }
            Settings.Default.SearchColumnWidths = builder.ToString();
            Settings.Default.Save();
        }

        private void SearchForm_SizeChanged(object sender, EventArgs e)
        {
            if (!this.Size.IsEmpty)
            {
                Settings.Default.SearchWindowSize = this.Size;
                Settings.Default.Save();
            }
        }

        private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            buttonOk_Click(null, null);
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (this.listView.SelectedIndices.Count > 0)
            {
                ListViewItem item = this.listView.SelectedItems[0];
                this.selectedObject = (ComDirectSearchResult)item.Tag;
                if (this.selectedObject.Type == null)
                {
                    MessageBox.Show("Der Typ dieses Eintrages konnte nicht erkannt werden.");
                    this.selectedObject = null;
                    return;
                }
                this.DialogResult = DialogResult.OK;
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void SearchForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            SearchForm_SizeChanged(null, null);
        }
    }
}
